import { replaceHtml, chatatABC } from '../utils/util';
import { getSheetIndex } from '../methods/get';
import { modelHTML, keycode } from './constant';
import { selectHightlightShow } from './select';
import sheetmanage from './sheetmanage';
import { isEditMode } from '../global/validate';
import { valueShowEs } from '../global/format';
import { setcellvalue } from '../global/setdata';
import { luckysheetrefreshgrid } from '../global/refresh';
import editor from '../global/editor';
import tooltip from '../global/tooltip';
import func_methods from '../global/func_methods';
import Store from '../store';
import locale from '../locale/locale';
import { checkCellEditPermission } from './checkEditPermission';
import { getCurrentSheetIndex, setCellFormula, suspendCalculate } from '../global/api';
import formula from '../global/formula';

// 查找替换
const luckysheetSearchReplace = {
    createDialog: function (source) {
        $("#luckysheet-modal-dialog-mask").hide();
        $("#luckysheet-search-replace").remove();

        const _locale = locale();
        const locale_findAndReplace = _locale.findAndReplace;
        const locale_button = _locale.button;

        let content = '<div class="tabBox">' +
                        '<span id="searchTab">' + locale_findAndReplace.find + '</span>' +
                        `<span id="replaceTab" style="display: ${Store.isEdit ? 'inline-block' : 'none'}">` + locale_findAndReplace.replace + '</span>' +
                      '</div>' +
                      '<div class="ctBox">' +
                        '<div class="inputBox">' +
                            '<div class="textboxs" id="searchInput">' + locale_findAndReplace.findTextbox + '：<input class="formulaInputFocus" spellcheck="false" value=""/></div>' +
                            '<div class="textboxs" id="replaceInput">' + locale_findAndReplace.replaceTextbox + '：<input class="formulaInputFocus" spellcheck="false" value=""/></div>' +
                            '<div class="textboxs search-range" id="searchRange">' + '查找范围' + '：<select><option value ="formula">公式</option><option value ="value">值</option></select></div>' +
                            '<div class="checkboxs">' +
                                '<div id="wordCheck">' +
                                    '<input type="checkbox"/>' +
                                    '<span>' + locale_findAndReplace.wholeTextbox + '</span>' +
                                '</div>' +
                                '<div id="caseCheck">' +
                                    '<input type="checkbox"/>' +
                                    '<span>' + locale_findAndReplace.distinguishTextbox + '</span>' +
                                '</div>' +
                            '</div>' +
                        '</div>' +
                        '<div class="btnBox">' +
                            '<button id="replaceAllBtn" class="btn btn-default">' + locale_findAndReplace.allReplaceBtn + '</button>' +
                            '<button id="replaceBtn" class="btn btn-default">' + locale_findAndReplace.replaceBtn + '</button>' +
                            '<button id="searchAllBtn" class="btn btn-default">' + locale_findAndReplace.allFindBtn + '</button>' +
                            '<button id="searchNextBtn" class="btn btn-default">' + locale_findAndReplace.findBtn + '</button>' +
                        '</div>' +
                      '</div>' +
                      `<span id="error-tip"></span>` + `<span id="success-tip"></span>`;

        $("body").append(replaceHtml(modelHTML, {
            "id": "luckysheet-search-replace",
            "addclass": "luckysheet-search-replace",
            "title": "",
            "content": content,
            "botton": '',
            "style": "z-index:193",
            "close": ''
        }));
        let $t = $("#luckysheet-search-replace").find(".luckysheet-modal-dialog-content").css("width", 500).end(),
            myh = $t.outerHeight(),
            myw = $t.outerWidth();
        let winw = $(window).width(), winh = $(window).height();
        let scrollLeft = $(document).scrollLeft(), scrollTop = $(document).scrollTop();
        $("#luckysheet-search-replace").css({ "left": (winw + scrollLeft - myw) / 2, "top": (winh + scrollTop - myh) / 3 }).show();

        if (source == "0") {
            $("#luckysheet-search-replace #searchTab").addClass("on").siblings().removeClass("on");
            $("#luckysheet-search-replace #replaceInput").hide();
            $("#luckysheet-search-replace #replaceAllBtn").hide();
            $("#luckysheet-search-replace #replaceBtn").hide();
        } else if (source == "1") {
            $("#luckysheet-search-replace #replaceTab").addClass("on").siblings().removeClass("on");
            $("#luckysheet-search-replace #replaceInput").show();
            $("#luckysheet-search-replace #replaceAllBtn").show();
            $("#luckysheet-search-replace #replaceBtn").show();
            $("#searchRange select").attr('disabled', 'disabled');
        }
    },
    init: function () {
        let _this = this;

        // 查找替换 切换
        $(document).off("click.SRtabBoxspan").on("click.SRtabBoxspan", "#luckysheet-search-replace .tabBox span", function () {
            $(this).addClass("on").siblings().removeClass("on");
            let $id = $(this).attr("id");
            if ($id == "searchTab") {
                $("#searchRange select").removeAttr('disabled');
                $("#luckysheet-search-replace #replaceInput").hide();
                $("#luckysheet-search-replace #replaceAllBtn").hide();
                $("#luckysheet-search-replace #replaceBtn").hide();

                $("#luckysheet-search-replace #searchInput input").focus();
            } else if ($id == "replaceTab") {
                $('#searchRange select option[value=formula]').prop('selected', true);
                $("#searchRange select").attr('disabled', 'disabled');
                $("#luckysheet-search-replace #replaceInput").show();
                $("#luckysheet-search-replace #replaceAllBtn").show();
                $("#luckysheet-search-replace #replaceBtn").show();

                $("#luckysheet-search-replace #replaceInput input").focus();
            }
        });

        $("#luckysheet-search-replace #searchInput input").focus(() => {
            $('#error-tip').text('');
            $('#success-tip').text('');
        });

        $('#searchRange select').focus(() => {
            $('#error-tip').text('');
            $('#success-tip').text('');
        });

        $("#luckysheet-search-replace #replaceInput input").focus(() => {
            $('#error-tip').text('');
            $('#success-tip').text('');
        });

        // 查找下一个
        $(document).off("keyup.SRsearchInput").on("keyup.SRsearchInput", "#luckysheet-search-replace #searchInput input", function (event) {
            let kcode = event.keyCode;
            if (kcode == keycode.ENTER) {
                _this.searchNext();
            }
        });
        $(document).off("click.SRsearchNextBtn").on("click.SRsearchNextBtn", "#luckysheet-search-replace #searchNextBtn", function () {
            $('#error-tip').text('');
            $('#success-tip').text('');
            _this.searchNext();
        });

        // 查找全部
        $(document).off("click.SRsearchAllBtn").on("click.SRsearchAllBtn", "#luckysheet-search-replace #searchAllBtn", function () {
            $('#error-tip').text('');
            $('#success-tip').text('');
            _this.searchAll();
        });
        $(document).off("click.SRsearchAllboxItem").on("click.SRsearchAllboxItem", "#luckysheet-search-replace #searchAllbox .boxItem", function () {
            $(this).addClass("on").siblings().removeClass("on");

            let r = $(this).attr("data-row");
            let c = $(this).attr("data-col");
            let sheetIndex = $(this).attr("data-sheetIndex");

            if (sheetIndex != Store.currentSheetIndex) {
                sheetmanage.changeSheetExec(sheetIndex);
            }

            Store.luckysheet_select_save = [
                { "row": [r, r], "column": [c, c] }
            ];

            selectHightlightShow();

            let scrollLeft = $("#luckysheet-cell-main").scrollLeft(),
                scrollTop = $("#luckysheet-cell-main").scrollTop();
            let winH = $("#luckysheet-cell-main").height(),
                winW = $("#luckysheet-cell-main").width();

            let row = Store.visibledatarow[r],
                row_pre = r - 1 == -1 ? 0 : Store.visibledatarow[r - 1];
            let col = Store.visibledatacolumn[c],
                col_pre = c - 1 == -1 ? 0 : Store.visibledatacolumn[c - 1];

            if (col - scrollLeft - winW + 20 > 0) {
                $("#luckysheet-scrollbar-x").scrollLeft(col - winW + 20);
            } else if (col_pre - scrollLeft - 20 < 0) {
                $("#luckysheet-scrollbar-x").scrollLeft(col_pre - 20);
            }

            if (row - scrollTop - winH + 20 > 0) {
                $("#luckysheet-scrollbar-y").scrollTop(row - winH + 20);
            } else if (row_pre - scrollTop - 20 < 0) {
                $("#luckysheet-scrollbar-y").scrollTop(row_pre - 20);
            }
        });

        // 替换
        $(document).off("click.SRreplaceBtn").on("click.SRreplaceBtn", "#luckysheet-search-replace #replaceBtn", function () {
            $('#error-tip').text('');
            $('#success-tip').text('');
            _this.replace();
        });

        // 全部替换
        $(document).off("click.SRreplaceAllBtn").on("click.SRreplaceAllBtn", "#luckysheet-search-replace #replaceAllBtn", function () {
            $('#error-tip').text('');
            $('#success-tip').text('');
            _this.replaceAll();
        });
    },
    searchNext: function () {
        let _this = this;

        let searchText = $("#luckysheet-search-replace #searchInput input").val();
        if (searchText == "" || searchText == null) {
            return;
        }
        const _locale = locale();
        const locale_findAndReplace = _locale.findAndReplace;
        let range;
        if (Store.luckysheet_select_save.length == 0 || (Store.luckysheet_select_save.length == 1 && Store.luckysheet_select_save[0].row[0] == Store.luckysheet_select_save[0].row[1] && Store.luckysheet_select_save[0].column[0] == Store.luckysheet_select_save[0].column[1])) {
            range = [{
                "row": [0, Store.flowdata.length - 1],
                "column": [0, Store.flowdata[0].length - 1]
            }];
        } else {
            range = $.extend(true, [], Store.luckysheet_select_save);
        }

        let searchIndexArr = _this.getSearchIndexArr(searchText, range);

        if (searchIndexArr.length == 0) {
            $('#error-tip').text(locale_findAndReplace.noFindTip);

            return;
        }

        let count = 0;

        if (Store.luckysheet_select_save.length == 0 || (Store.luckysheet_select_save.length == 1 && Store.luckysheet_select_save[0].row[0] == Store.luckysheet_select_save[0].row[1] && Store.luckysheet_select_save[0].column[0] == Store.luckysheet_select_save[0].column[1])) {
            if (Store.luckysheet_select_save.length == 0) {
                count = 0;
            } else {
                for (let i = 0; i < searchIndexArr.length; i++) {
                    if (searchIndexArr[i].r == Store.luckysheet_select_save[0].row[0] && searchIndexArr[i].c == Store.luckysheet_select_save[0].column[0]) {
                        if (i == searchIndexArr.length - 1) {
                            count = 0;
                        } else {
                            count = i + 1;
                        }

                        break;
                    }
                }
            }

            Store.luckysheet_select_save = [{
                "row": [searchIndexArr[count].r, searchIndexArr[count].r],
                "column": [searchIndexArr[count].c, searchIndexArr[count].c]
            }];
        } else {
            let rf = range[range.length - 1].row_focus;
            let cf = range[range.length - 1].column_focus;

            for (let i = 0; i < searchIndexArr.length; i++) {
                if (searchIndexArr[i].r == rf && searchIndexArr[i].c == cf) {
                    if (i == searchIndexArr.length - 1) {
                        count = 0;
                    } else {
                        count = i + 1;
                    }

                    break;
                }
            }

            for (let s = 0; s < range.length; s++) {
                let r1 = range[s].row[0], r2 = range[s].row[1];
                let c1 = range[s].column[0], c2 = range[s].column[1];

                if (searchIndexArr[count].r >= r1 && searchIndexArr[count].r <= r2 && searchIndexArr[count].c >= c1 && searchIndexArr[count].c <= c2) {
                    let obj = range[s];
                    obj.row_focus = searchIndexArr[count].r;
                    obj.column_focus = searchIndexArr[count].c;
                    range.splice(s, 1);
                    range.push(obj);

                    break;
                }
            }

            Store.luckysheet_select_save = range;
        }

        selectHightlightShow();

        let scrollLeft = $("#luckysheet-cell-main").scrollLeft(),
            scrollTop = $("#luckysheet-cell-main").scrollTop();
        let winH = $("#luckysheet-cell-main").height(),
            winW = $("#luckysheet-cell-main").width();

        let row = Store.visibledatarow[searchIndexArr[count].r],
            row_pre = searchIndexArr[count].r - 1 == -1 ? 0 : Store.visibledatarow[searchIndexArr[count].r - 1];
        let col = Store.visibledatacolumn[searchIndexArr[count].c],
            col_pre = searchIndexArr[count].c - 1 == -1 ? 0 : Store.visibledatacolumn[searchIndexArr[count].c - 1];

        if (col - scrollLeft - winW + 20 > 0) {
            $("#luckysheet-scrollbar-x").scrollLeft(col - winW + 20);
        } else if (col_pre - scrollLeft - 20 < 0) {
            $("#luckysheet-scrollbar-x").scrollLeft(col_pre - 20);
        }

        if (row - scrollTop - winH + 20 > 0) {
            $("#luckysheet-scrollbar-y").scrollTop(row - winH + 20);
        } else if (row_pre - scrollTop - 20 < 0) {
            $("#luckysheet-scrollbar-y").scrollTop(row_pre - 20);
        }

        if ($("#searchAllbox").is(":visible")) {
            $("#luckysheet-search-replace #searchAllbox .boxItem").removeClass("on");
        }
    },
    searchAll: function () {
        let _this = this;

        const _locale = locale();
        const locale_findAndReplace = _locale.findAndReplace;

        $("#luckysheet-search-replace #searchAllbox").remove();

        let searchText = $("#luckysheet-search-replace #searchInput input").val();
        if (searchText == "" || searchText == null) {
            return;
        }

        let range;
        if (Store.luckysheet_select_save.length == 0 || (Store.luckysheet_select_save.length == 1 && Store.luckysheet_select_save[0].row[0] == Store.luckysheet_select_save[0].row[1] && Store.luckysheet_select_save[0].column[0] == Store.luckysheet_select_save[0].column[1])) {
            range = [{
                "row": [0, Store.flowdata.length - 1],
                "column": [0, Store.flowdata[0].length - 1]
            }];
        } else {
            range = $.extend(true, [], Store.luckysheet_select_save);
        }

        let searchIndexArr = _this.getSearchIndexArr(searchText, range);

        if (searchIndexArr.length == 0) {
            $('#error-tip').text(locale_findAndReplace.noFindTip);

            return;
        }

        let searchAllHtml = '';

        setSearchHtml(0, searchIndexArr.length);
        $('.boxPage').remove();
        let pageHtml = '';
        if (searchIndexArr.length > 50) {
            pageHtml = `<div class="boxPage" data-page="0"><a id="prePage">上一页</a><a id="nextPage">下一页</a></div>`;
            setSearchHtml(0, 50);
        } else {
            $("#luckysheet-search-replace").remove('.boxPage');
        }

        function setSearchHtml (startIndex, endIndex) {
            if (startIndex < 0) startIndex = 0;
            if (endIndex < 50) endIndex = 50;
            if (endIndex >= searchIndexArr.length) endIndex = searchIndexArr.length;
            searchAllHtml = '';
            for (let i = startIndex; i < endIndex; i++) {
                let value_ShowEs = valueShowEs(searchIndexArr[i].r, searchIndexArr[i].c, Store.flowdata).toString();
                const formula = Store.flowdata[searchIndexArr[i].r][searchIndexArr[i].c].f;
                if (value_ShowEs.indexOf("</") > -1 && value_ShowEs.indexOf(">") > -1) {
                    searchAllHtml += '<div class="boxItem" data-row="' + searchIndexArr[i].r + '" data-col="' + searchIndexArr[i].c + '" data-sheetIndex="' + Store.currentSheetIndex + '">' +
                                        '<span>' + Store.luckysheetfile[getSheetIndex(Store.currentSheetIndex)].name + '</span>' +
                                        '<span>' + chatatABC(searchIndexArr[i].c) + (searchIndexArr[i].r + 1) + '</span>' +
                                        '<span>' + value_ShowEs + '</span>' +
                                        `<span title='${(formula || '')}'>${(formula || '')}</span>` +
                                     '</div>';
                } else {
                    searchAllHtml += '<div class="boxItem" data-row="' + searchIndexArr[i].r + '" data-col="' + searchIndexArr[i].c + '" data-sheetIndex="' + Store.currentSheetIndex + '">' +
                                        '<span>' + Store.luckysheetfile[getSheetIndex(Store.currentSheetIndex)].name + '</span>' +
                                        '<span>' + chatatABC(searchIndexArr[i].c) + (searchIndexArr[i].r + 1) + '</span>' +
                                        '<span title=' + value_ShowEs + '">' + value_ShowEs + '</span>' +
                                        `<span title='${(formula || '')}'>${(formula || '')}</span>` +
                                     '</div>';
                }
            }
        }

        $('<div id="searchAllbox"><div class="boxTitle"><span>' + locale_findAndReplace.searchTargetSheet + '</span><span>' + locale_findAndReplace.searchTargetCell + '</span><span>' + locale_findAndReplace.searchTargetValue + '</span><span>' + '公式' + '</span></div><div class="boxMain">' + searchAllHtml + '</div></div>').appendTo($("#luckysheet-search-replace"));
        $("#luckysheet-search-replace").append($(pageHtml));
        $('#prePage').on('click', function () {
            $('.boxMain').empty();
            let page = Number($('.boxPage').data('page') || '0');

            let prePage = page - 1;
            if (prePage < 0) prePage = 0;
            setSearchHtml(prePage * 50, (prePage + 1) * 50);
            $('.boxMain').html(searchAllHtml);
            $('.boxPage').data('page', prePage);
            $("#luckysheet-search-replace #searchAllbox .boxItem").eq(0).addClass("on").siblings().removeClass("on");
            $('#searchAllbox').scrollTop(0);
        });
        $('#nextPage').on('click', function () {
            $('.boxMain').empty();
            let page = Number($('.boxPage').data('page') || '0');
            let nextPage = page + 1;
            if (nextPage > Math.floor(searchIndexArr.length / 50)) nextPage = Math.floor(searchIndexArr.length / 50);
            setSearchHtml(nextPage * 50, (nextPage + 1) * 50);
            $('.boxMain').html(searchAllHtml);
            $('.boxPage').data('page', nextPage);
            $("#luckysheet-search-replace #searchAllbox .boxItem").eq(0).addClass("on").siblings().removeClass("on");
            $('#searchAllbox').scrollTop(0);
        });
        $("#luckysheet-search-replace #searchAllbox .boxItem").eq(0).addClass("on").siblings().removeClass("on");

        Store.luckysheet_select_save = [{
            "row": [searchIndexArr[0].r, searchIndexArr[0].r],
            "column": [searchIndexArr[0].c, searchIndexArr[0].c]
        }];

        selectHightlightShow();
    },
    getSearchIndexArr: function (searchText, range) {
        let arr = [];
        let obj = {};

        // 正则表达式匹配
        let regCheck = false;
        if ($("#luckysheet-search-replace #regCheck input[type='checkbox']").is(":checked")) {
            regCheck = true;
        }

        // 整词匹配
        let wordCheck = false;
        if ($("#luckysheet-search-replace #wordCheck input[type='checkbox']").is(":checked")) {
            wordCheck = true;
        }

        // 区分大小写匹配
        let caseCheck = false;
        if ($("#luckysheet-search-replace #caseCheck input[type='checkbox']").is(":checked")) {
            caseCheck = true;
        }

        let searchType = 'formula';
        if ($("#searchRange select").val()) searchType = $("#searchRange select").val();
        for (let s = 0; s < range.length; s++) {
            let r1 = range[s].row[0], r2 = range[s].row[1];
            let c1 = range[s].column[0], c2 = range[s].column[1];

            for (let r = r1; r <= r2; r++) {
                for (let c = c1; c <= c2; c++) {
                    let cell = Store.flowdata[r][c];

                    if (cell != null) {
                        let value;
                        if (searchType === 'value') {
                            value = valueShowEs(r, c, Store.flowdata);
                        } else {
                            let formula = Store.flowdata[r][c].f;
                            if (formula) {
                                value = formula.replace('=', '');
                            } else {
                                value = valueShowEs(r, c, Store.flowdata);
                            }
                        }

                        if (value == 0) {
                            value = value.toString();
                        }

                        if (value != null && value != "") {
                            value = value.toString();

                            // 1. 勾选整词 直接匹配
                            // 2. 勾选了正则 结合是否勾选 构造正则
                            // 3. 什么都没选 用字符串 indexOf 匹配
                            if (regCheck) { // 正则表达式  目前功能已经被去掉了
                                let reg;
                                // 是否区分大小写
                                reg = new RegExp(func_methods.getRegExpStr(searchText.replace('(', '\\(').replace(')', '\\)')), caseCheck ? 'g' : 'ig');

                                if (reg.test(value)) {
                                    if (!((r + "_" + c) in obj)) {
                                        obj[r + "_" + c] = 0;
                                        arr.push({ "r": r, "c": c });
                                    }
                                }
                            } else {
                                let regStr = func_methods.replaceSearchStr(searchText);
                                regStr = wordCheck ? `^${regStr}$` : regStr;
                                // 是否区分大小写
                                let reg = new RegExp(func_methods.getRegExpStr(regStr), caseCheck ? 'g' : 'ig');
                                if (reg.test(value)) {
                                    if (!((r + "_" + c) in obj)) {
                                        obj[r + "_" + c] = 0;
                                        arr.push({ "r": r, "c": c });
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        return arr;
    },
    replace: function () {
        let _this = this;

        const _locale = locale();
        const locale_findAndReplace = _locale.findAndReplace;

        if (!Store.allowEdit) {
            tooltip.info(locale_findAndReplace.modeTip, "");
            return;
        }

        let searchText = $("#luckysheet-search-replace #searchInput input").val();
        if (searchText == "" || searchText == null) {
            if (isEditMode()) {
                alert(locale_findAndReplace.searchInputTip);
            } else {
                tooltip.info(locale_findAndReplace.searchInputTip, "");
            }

            return;
        }

        let range;
        if (Store.luckysheet_select_save.length == 0 || (Store.luckysheet_select_save.length == 1 && Store.luckysheet_select_save[0].row[0] == Store.luckysheet_select_save[0].row[1] && Store.luckysheet_select_save[0].column[0] == Store.luckysheet_select_save[0].column[1])) {
            range = [{
                "row": [0, Store.flowdata.length - 1],
                "column": [0, Store.flowdata[0].length - 1]
            }];
        } else {
            range = $.extend(true, [], Store.luckysheet_select_save);
        }

        let searchIndexArr = _this.getSearchIndexArr(searchText, range);

        if (searchIndexArr.length == 0) {
            $('#error-tip').text(locale_findAndReplace.noReplceTip);
            return;
        }

        let count = null;

        let last = Store.luckysheet_select_save[Store.luckysheet_select_save.length - 1];
        let rf = last.row_focus;
        let cf = last.column_focus;

        for (let i = 0; i < searchIndexArr.length; i++) {
            if (searchIndexArr[i].r == rf && searchIndexArr[i].c == cf) {
                count = i;
                break;
            }
        }

        if (count == null) {
            if (searchIndexArr.length == 0) {
                if (isEditMode()) {
                    alert(locale_findAndReplace.noMatchTip);
                } else {
                    tooltip.info(locale_findAndReplace.noMatchTip, "");
                }

                return;
            } else {
                count = 0;
            }
        }

        // 正则表达式匹配
        let regCheck = false;
        if ($("#luckysheet-search-replace #regCheck input[type='checkbox']").is(":checked")) {
            regCheck = true;
        }

        // 整词匹配
        let wordCheck = false;
        if ($("#luckysheet-search-replace #wordCheck input[type='checkbox']").is(":checked")) {
            wordCheck = true;
        }

        // 区分大小写匹配
        let caseCheck = false;
        if ($("#luckysheet-search-replace #caseCheck input[type='checkbox']").is(":checked")) {
            caseCheck = true;
        }

        let replaceText = $("#luckysheet-search-replace #replaceInput input").val();

        let d = Store.flowdata;

        let r, c;
        r = searchIndexArr[count].r;
        c = searchIndexArr[count].c;

        let v = replaceText;

        if (!checkCellEditPermission(r, c, d)) {
            return;
        }

        let reg;
        if (regCheck) { // 正则表达式  目前功能已经被去掉了
            // 是否区分大小写
            reg = new RegExp(func_methods.getRegExpStr(searchText.replace('(', '\\(').replace(')', '\\)')), caseCheck ? 'g' : 'ig');
        } else {
            let regStr = func_methods.replaceSearchStr(searchText);
            regStr = wordCheck ? `^${regStr}$` : regStr;
            // 是否区分大小写
            reg = new RegExp(func_methods.getRegExpStr(regStr), caseCheck ? 'g' : 'ig');
        }

        if (Store.flowdata[r][c].f) {
            setCellFormula(Store.flowdata[r][c].f.replace(reg, replaceText), {}, r, c);
        } else {
            setcellvalue(r, c, null, Store.flowdata[r][c].v.toString().replace(reg, replaceText));
            formula.execFunctionExist = formula.execFunctionExist || [];
            formula.execFunctionExist.push({
                r,
                c,
                i: Store.currentSheetIndex
            });
            formula.execFunctionGroup();
        }
        Store.luckysheet_select_save = [{ "row": [r, r], "column": [c, c] }];

        if ($("#luckysheet-search-replace #searchAllbox").is(":visible")) {
            $("#luckysheet-search-replace #searchAllbox").hide();
        }
        if ($('.boxPage').is(":visible")) {
            $('.boxPage').hide();
        }
        selectHightlightShow();

        let scrollLeft = $("#luckysheet-cell-main").scrollLeft(),
            scrollTop = $("#luckysheet-cell-main").scrollTop();
        let winH = $("#luckysheet-cell-main").height(),
            winW = $("#luckysheet-cell-main").width();

        let row = Store.visibledatarow[r],
            row_pre = r - 1 == -1 ? 0 : Store.visibledatarow[r - 1];
        let col = Store.visibledatacolumn[c],
            col_pre = c - 1 == -1 ? 0 : Store.visibledatacolumn[c - 1];

        if (col - scrollLeft - winW + 20 > 0) {
            $("#luckysheet-scrollbar-x").scrollLeft(col - winW + 20);
        } else if (col_pre - scrollLeft - 20 < 0) {
            $("#luckysheet-scrollbar-x").scrollLeft(col_pre - 20);
        }

        if (row - scrollTop - winH + 20 > 0) {
            $("#luckysheet-scrollbar-y").scrollTop(row - winH + 20);
        } else if (row_pre - scrollTop - 20 < 0) {
            $("#luckysheet-scrollbar-y").scrollTop(row_pre - 20);
        }
        luckysheetrefreshgrid();
    },
    replaceAll: function () {
        let _this = this;

        const _locale = locale();
        const locale_findAndReplace = _locale.findAndReplace;

        if (!Store.allowEdit) {
            tooltip.info(locale_findAndReplace.modeTip, "");
            return;
        }

        let searchText = $("#luckysheet-search-replace #searchInput input").val();
        if (searchText == "" || searchText == null) {
            if (isEditMode()) {
                alert(locale_findAndReplace.searchInputTip);
            } else {
                tooltip.info(locale_findAndReplace.searchInputTip, "");
            }

            return;
        }

        let range;
        if (Store.luckysheet_select_save.length == 0 || (Store.luckysheet_select_save.length == 1 && Store.luckysheet_select_save[0].row[0] == Store.luckysheet_select_save[0].row[1] && Store.luckysheet_select_save[0].column[0] == Store.luckysheet_select_save[0].column[1])) {
            range = [{
                "row": [0, Store.flowdata.length - 1],
                "column": [0, Store.flowdata[0].length - 1]
            }];
        } else {
            range = $.extend(true, [], Store.luckysheet_select_save);
        }

        let searchIndexArr = _this.getSearchIndexArr(searchText, range);

        if (searchIndexArr.length == 0) {
            $('#error-tip').text(locale_findAndReplace.noReplceTip);

            return;
        }

        // 正则表达式匹配
        let regCheck = false;
        if ($("#luckysheet-search-replace #regCheck input[type='checkbox']").is(":checked")) {
            regCheck = true;
        }

        // 整词匹配
        let wordCheck = false;
        if ($("#luckysheet-search-replace #wordCheck input[type='checkbox']").is(":checked")) {
            wordCheck = true;
        }

        // 区分大小写匹配
        let caseCheck = false;
        if ($("#luckysheet-search-replace #caseCheck input[type='checkbox']").is(":checked")) {
            caseCheck = true;
        }

        let replaceText = $("#luckysheet-search-replace #replaceInput input").val();

        let d = Store.flowdata;
        let replaceCount = 0;
        range = [];
        suspendCalculate();
        for (let i = 0; i < searchIndexArr.length; i++) {
            let r = searchIndexArr[i].r;
            let c = searchIndexArr[i].c;

            if (!checkCellEditPermission(r, c, d)) {
                continue;
            }

            let v = replaceText;
            let reg;

            if (regCheck) { // 正则表达式  目前功能已经被去掉了
                // 是否区分大小写
                reg = new RegExp(func_methods.getRegExpStr(searchText.replace('(', '\\(').replace(')', '\\)')), caseCheck ? 'g' : 'ig');
            } else {
                let regStr = func_methods.replaceSearchStr(searchText);
                regStr = wordCheck ? `^${regStr}$` : regStr;
                // 是否区分大小写
                reg = new RegExp(func_methods.getRegExpStr(regStr), caseCheck ? 'g' : 'ig');
            }

            if (Store.flowdata[r][c].f) {
                setCellFormula(Store.flowdata[r][c].f.replace(reg, replaceText), {}, r, c, false);
            } else {
                setcellvalue(r, c, null, Store.flowdata[r][c].v.toString().replace(reg, replaceText));
                formula.suspendCellList.push({
                    r: r,
                    c: c,
                    i: Store.currentSheetIndex
                });
            }
            range.push({ "row": [r, r], "column": [c, c] });
            replaceCount++;
        }

        if ($("#luckysheet-search-replace #searchAllbox").is(":visible")) {
            $("#luckysheet-search-replace #searchAllbox").hide();
        }

        if ($('.boxPage').is(":visible")) {
            $('.boxPage').hide();
        }
        suspendCalculate(false);
        Store.luckysheet_select_save = $.extend(true, [], range);
        selectHightlightShow();

        let succeedInfo = replaceHtml(locale_findAndReplace.successTip, {
            "xlength": replaceCount
        });
        $('#success-tip').text(succeedInfo);
        luckysheetrefreshgrid();
    }
};

export default luckysheetSearchReplace;
